package com.zmn.oms.third.yunding.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.io.netty.util.internal.StringUtil;
import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.dubbo.interfaces.area.AreaListRemoteService;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.consts.GlobalConsts;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.interfaces.baidumap.BaiduMapBService;
import com.zmn.oms.business.interfaces.notifylog.OrderNotifyLogBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.baidumap.LngLatLocation;
import com.zmn.oms.model.dto.factory.OrderFactoryDTO;
import com.zmn.oms.model.dto.order.proxy.CancelOrderDTO;
import com.zmn.oms.model.dto.order.proxy.OrderLogDTO;
import com.zmn.oms.model.dto.order.zmn.FactoryNewOrderDTO;
import com.zmn.oms.model.entity.notifylog.OrderNotifyLog;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.orderattachment.OrderAttachment;
import com.zmn.oms.model.entity.remark.OrderRemark;
import com.zmn.oms.model.entity.remark.OrderRemarkDetail;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.orderattachment.OrderAttachmentService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkDetailService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.base.util.MasterPhoneUtil;
import com.zmn.oms.third.yunding.YundingConsts;
import com.zmn.oms.third.yunding.YundingUtil;
import com.zmn.oms.third.yunding.api.*;
import com.zmn.oms.third.yunding.dto.YundingCancelOrderDTO;
import com.zmn.oms.third.yunding.dto.YundingCreateOrderDTO;
import com.zmn.oms.third.yunding.dto.YundingOldPartSendbackDTO;
import com.zmn.oms.third.yunding.dto.YundingSyncOrderStatusDTO;
import com.zmn.oms.third.yunding.service.YundingService;
import com.zmn.oms.zmn.business.interfaces.proxy.ProxyOrderBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.FactoryOrderBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 云丁鹿客渠道接口实现类
 *
 * @author xiewenbing
 * @date 2020/09/10
 */
@Service
@Slf4j
public class YundingServiceImpl implements YundingService {

    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ProxyOrderBService proxyOrderBService;
    @Autowired
    private OrderNotifyLogBService orderNotifyLogBService;
    @Autowired
    private OrderExtendService orderExtendService;
    @Autowired
    private OrderRemarkService orderRemarkService;
    @Autowired
    private OrderRemarkDetailService orderRemarkDetailService;
    @Autowired
    private ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    private FactoryOrderBService factoryOrderBService;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;
    @Autowired
    private OrderServiceItemService orderServiceItemService;
    @Autowired
    private OrderAttachmentService orderAttachmentService;
    @Autowired
    private BaiduMapBService baiduMapBService;

    @Resource
    private RedisManager redisManager;

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected AreaListRemoteService areaListRemoteService;
//    @Reference(version = com.zmn.mer.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
//    protected FactoryListRemoteService factoryListRemoteService;

    /**
     * 创建订单
     *
     * @param createOrderDTO
     * @return 订单Id
     * @throws OmsBaseException
     */
    @Override
    public String createOrder(YundingCreateOrderDTO createOrderDTO) throws OmsBaseException {

        // 判断功能是否开启
        if (!YundingConsts.POWER_ON) {
            log.info("【{}】创建订单 该功能没有开启。", YundingConsts.CHANNEL_NAME);
            throw new OmsBaseException(Integer.valueOf(YundingConsts.RESPONSE_CODE_UNSUPPORT_SERVICE),"服务暂不支持");
        }

        // 错误码
        String errCode ;

        do {
            // 参数判断
            if (Objects.isNull(createOrderDTO)) {
                log.info("【{}】 创建订单失败--参数为null",YundingConsts.CHANNEL_NAME);
                errCode = YundingConsts.RESPONSE_CODE_PARAM_MISS;
                break;
            }

            // 判断是否为测试
            if (createOrderDTO.getSign().compareTo("test-oms-xiewenbing") != 0) {
                // app key 比较
                if (YundingConsts.APP_KEY.compareTo(createOrderDTO.getAppKey()) != 0) {
                    log.info("【{}】 创建订单失败--APP KEY不匹配", YundingConsts.CHANNEL_NAME);
                    errCode = YundingConsts.RESPONSE_CODE_PARAM_MISS;
                    break;
                }

                // 验证签名
                /** 取消验证签名，因为可能传输了不需要的参数导致签名不一致
                Map<String, String> signParams = YundingUtil.objectToMap(createOrderDTO);
                signParams.remove("sign");
                if (!YundingUtil.verifySign(signParams, createOrderDTO.getSign())) {
                    log.info("【{}】 创建订单失败--验证签名失败", YundingConsts.CHANNEL_NAME);
                    errCode = YundingConsts.RESPONSE_CODE_PARAM_ERROR;
                    break;
                }
                 **/
            }

            // 构建OMS创建订单数据
            FactoryNewOrderDTO zmnCreateOrderDTO = buildCreateOrder(createOrderDTO);
            if (Objects.isNull(zmnCreateOrderDTO)) {
                log.info("【{}】 创建订单失败--订单创建参数不正确",YundingConsts.CHANNEL_NAME);
                errCode = YundingConsts.RESPONSE_CODE_PARAM_MISS;
                break;
            }

            Long orderId = 0L;
            Long workId = 0L;
            OrderWork orderWork = null;
            try {
                log.info("【{}】 创建订单，参数：【{}】",YundingConsts.CHANNEL_NAME,zmnCreateOrderDTO);
                OrderBO order = factoryOrderBService.insertOrder(zmnCreateOrderDTO);
                if (Objects.nonNull(order)) {
                    orderWork = order.getOrderWork();
                    orderId = orderWork.getOrderId();
                    workId = orderWork.getWorkId();
                }
            } catch (OmsBaseException omsBaseException) {

                log.info("【{}】 创建订单失异常,OmsBaseException【{}】",YundingConsts.CHANNEL_NAME,omsBaseException.getMessage());
                errCode = YundingConsts.RESPONSE_CODE_SYSTEM_ERROR;
                break;

            } catch (Exception exception) {

                log.info("【{}】 创建订单失异常 Exception【{}】",YundingConsts.CHANNEL_NAME,exception.getMessage());
                errCode = YundingConsts.RESPONSE_CODE_SYSTEM_ERROR;
                break;
            }

            log.info("【{}】 创建订单成功 【{}】",YundingConsts.CHANNEL_NAME,orderId);

            // 保存扩展数据
            YundingOrderExtend yundingOrderExtend = buildYundingOrderExtend(createOrderDTO);
            if (Objects.nonNull(yundingOrderExtend)) {

                yundingOrderExtend.setOrderInstall(orderWork.getProductId() == YundingConsts.PRODUCT_ID_INSTALL ? Boolean.TRUE : Boolean.FALSE);

                OrderExtend orderExtend = new OrderExtend();
                orderExtend.setExtId(orderId);
                orderExtend.setOuterData(JSON.toJSONString(yundingOrderExtend));
                orderExtendService.updateOrderExtend(orderExtend);

                // redis保存云丁订单资料
                this.saveOrderCacheData(orderId,JSON.toJSONString(yundingOrderExtend));
            }

            // 订单开始自动流转
            workFlowContextBService.asyncAutoFlow(orderId,workId);

            return String.valueOf(orderId);
        } while (false);

        // 抛出异常
        throw new OmsBaseException(Integer.valueOf(errCode),YundingConsts.getErrMsgByCode(errCode));
    }

    /**
     * 取消订单
     * @param cancelOrderDTO
     * @throws OmsBaseException
     */
    @Override
    public void cancelOrder(YundingCancelOrderDTO cancelOrderDTO) throws OmsBaseException {

        // 判断功能是否开启
        if (!YundingConsts.POWER_ON) {
            log.info("【{}】取消订单 该功能没有开启。", YundingConsts.CHANNEL_NAME);
            throw new OmsBaseException(Integer.valueOf(YundingConsts.RESPONSE_CODE_UNSUPPORT_SERVICE),"服务暂不支持");
        }

        // 错误码
        String errCode ;

        do {
            // 参数判断
            if (Objects.isNull(cancelOrderDTO)) {
                log.info("【{}】 取消订单失败--参数为null",YundingConsts.CHANNEL_NAME);
                errCode = YundingConsts.RESPONSE_CODE_PARAM_MISS;
                break;
            }

            // 判断是否为测试
            if (cancelOrderDTO.getSign().compareTo("test-oms-xiewenbing") != 0) {
                // app key 比较
                if (YundingConsts.APP_KEY.compareTo(cancelOrderDTO.getAppKey()) != 0) {
                    log.info("【{}】 取消订单失败--APP KEY不匹配", YundingConsts.CHANNEL_NAME);
                    errCode = YundingConsts.RESPONSE_CODE_PARAM_MISS;
                    break;
                }

                // 验证签名
                /** 取消验证签名
                Map<String, String> signParams = YundingUtil.objectToMap(cancelOrderDTO);
                signParams.remove("sign");
                if (!YundingUtil.verifySign(signParams, cancelOrderDTO.getSign())) {
                    log.info("【{}】 取消订单失败--验证签名失败", YundingConsts.CHANNEL_NAME);
                    errCode = YundingConsts.RESPONSE_CODE_PARAM_ERROR;
                    break;
                }
                */
            }

            // 读取订单id和订单数据
            Long orderId = Long.valueOf(cancelOrderDTO.getOrderNumber());
            OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,orderId);
            if (Objects.isNull(orderWork)) {
                log.info("【{}】 取消订单失败--查找不到对应的订单",YundingConsts.CHANNEL_NAME);
                errCode = YundingConsts.RESPONSE_CODE_PARAM_MISS;
                break;
            }

            log.info("【{}】取消订单：订单Id:[{}]，OuterId:[{}]，取消原因:[{}]", YundingConsts.CHANNEL_NAME,
                    orderWork.getOrderId(),orderWork.getOuterId(), cancelOrderDTO.getCancelReason());

            // 取消订单数据构建
            CancelOrderDTO cancelDTO = new CancelOrderDTO();
            cancelDTO.setOrderId(orderWork.getOrderId());
            cancelDTO.setOuterId(orderWork.getOuterId());
            cancelDTO.setChannelId(OrderConsts.CHANNEL_ID_YUNDING_LOCK);
            cancelDTO.setOperatorId(Long.valueOf(OrderConsts.CHANNEL_ID_YUNDING_LOCK));
            cancelDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_CHANNEL);

            String cancelReason = cancelOrderDTO.getCancelReason();
            if (Objects.isNull(cancelReason) || cancelReason.isEmpty()) {
                cancelReason = "渠道方取消";
            }

            // 取消订单
            try {
                cancelDTO.setRemark(cancelReason);
                proxyOrderBService.cancelOrder(cancelDTO);
            } catch (OmsBaseException omsBaseException) {
                log.error("【{}】取消订单失败 消息:[{}]",YundingConsts.CHANNEL_NAME, omsBaseException.getMessage());

                errCode = YundingConsts.RESPONSE_CODE_SYSTEM_ERROR;
                break;
            }

            return;
        } while (false);

        // 抛出异常
        throw new OmsBaseException(Integer.valueOf(errCode),YundingConsts.getErrMsgByCode(errCode));
    }

    /**
     * 同步渠道订单确认
     * @param orderWorkLogChange
     * @throws OmsBaseException
     */
    @Override
    public void syncOrderConfirm(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 参数验证
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("参数不能为null");
        }

        // 判断是否已同步
        if (this.findSuccessSyncResult(orderWorkLogChange.getOrderId(),OrderStatusConsts.ORDER_STATUS_CONFIRM)) {
            throw new OmsBaseException("已同步确认，无需再同步");
        }

        // 生成同步数据
        YundingSyncOrderStatusDTO syncOrderStatusDTO = newYundingSyncOrderStatusDTO();

        // 同步确认数据
        YundingSyncStatusData syncStatusData = newYundingSyncStatusData(orderWorkLogChange.getOrderId(),
                YundingConsts.ORDER_STATUS_WAITING_GRAB);

        syncOrderStatusDTO.setData(JSON.toJSONString(syncStatusData));
        syncOrderStatusDTO.setSign(YundingUtil.makeSign(YundingUtil.objectToMap(syncOrderStatusDTO)));

        // 发送请求
        String syncUrl = YundingConsts.API_URL + YundingConsts.SYNC_ORDER_STATUS_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,JSON.toJSONString(syncOrderStatusDTO));
        if (StringUtil.isNullOrEmpty(syncResponse)) {
            throw new OmsBaseException("发送同步确认请求失败");
        }

        log.info("【{}】同步确认，返回：【{}】",YundingConsts.CHANNEL_NAME,syncResponse);
        // 解析并保存同步结果信息
        YundingSyncResponse yundingSyncResponse = analysisSyncResponse(syncResponse);
        saveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_CONFIRM,yundingSyncResponse);
    };

    /**
     * 同步订单预约时间
     * @param orderWorkLogChange
     * @throws OmsBaseException
     */
    @Override
    public void syncOrderDutytime(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 参数验证
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("参数不能为null");
        }

        // 预约时间判断
        if (Objects.isNull(orderWorkLogChange.getDutyTime())) {
            throw new OmsBaseException("预约时间为空不同步");
        }

        if (this.findSuccessSyncResult(orderWorkLogChange.getOrderId(),OrderStatusConsts.ORDER_STATUS_COMPLETE)) {
            throw new OmsBaseException("已同步完成，无需同步");
        }

        // 生成同步数据
        YundingSyncOrderStatusDTO syncOrderStatusDTO = newYundingSyncOrderStatusDTO();

        // 同步预约数据
        YundingSyncStatusData syncStatusData = newYundingSyncStatusData(orderWorkLogChange.getOrderId(),
                YundingConsts.ORDER_STATUS_WAITING_SERVE);

        // 预约时间
        YundingDutytimeExtFields dutytimeExtFields = new YundingDutytimeExtFields();
        dutytimeExtFields.setPlanServiceDate(orderWorkLogChange.getDutyTime());

        syncStatusData.setExtFields(JSON.toJSONString(dutytimeExtFields));
        syncOrderStatusDTO.setData(JSON.toJSONString(syncStatusData));
        syncOrderStatusDTO.setSign(YundingUtil.makeSign(YundingUtil.objectToMap(syncOrderStatusDTO)));

        // 发送请求
        String syncUrl = YundingConsts.API_URL + YundingConsts.SYNC_ORDER_STATUS_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,JSON.toJSONString(syncOrderStatusDTO));
        if (StringUtil.isNullOrEmpty(syncResponse)) {
            throw new OmsBaseException("发送同步预约时间请求失败");
        }

        log.info("【{}】同步预约时间，返回：【{}】",YundingConsts.CHANNEL_NAME,syncResponse);
        // 解析同步结果信息
        analysisSyncResponse(syncResponse);
    }

    /**
     * 同步订单派单
     * @param orderWorkLogChange
     * @throws OmsBaseException
     */
    @Override
    public void syncOrderDistribute(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 参数验证
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("参数不能为null");
        }

        Long orderId = orderWorkLogChange.getOrderId();
        Long workId = orderWorkLogChange.getWorkId();

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,workId);
        if(Objects.isNull(orderWork)) {
            throw new OmsBaseException("查找不到工单信息");
        }

        if (this.findSuccessSyncResult(orderWorkLogChange.getOrderId(),OrderStatusConsts.ORDER_STATUS_COMPLETE)) {
            throw new OmsBaseException("已同步完成，无需同步");
        }

        // 生成同步数据
        YundingSyncOrderStatusDTO syncOrderStatusDTO = newYundingSyncOrderStatusDTO();

        // 同步派单数据
        YundingSyncStatusData syncStatusData = newYundingSyncStatusData(orderWorkLogChange.getOrderId(),
                YundingConsts.ORDER_STATUS_WAITING_COMMUNICATE);

        // 师傅信息
        YundingDistributeExtFields distributeExtFields = new YundingDistributeExtFields();
        String masterName = orderWork.getMasterName();
        distributeExtFields.setContactName(
                Optional.ofNullable(masterName)
                        .filter(name -> name.length() >= 1)
                        .map(name -> String.format("%s工程师", name.substring(0,1)))
                        .orElse(YundingConsts.MASTER_DEFAULT_NAME)
        );
        distributeExtFields.setContactPhone(YundingConsts.MASTER_PHONE);
        distributeExtFields.setContactPhone(
                Optional.ofNullable(orderDetailService.findOrderDetailByKey(orderWork.getOrderId()))
                        .map(orderDetail -> {
                            if (Objects.equals(orderDetail.getBindStatus(), OrderConsts.BIND_STATUS_BIND)
                                    && org.apache.commons.lang3.StringUtils.isNotBlank(orderDetail.getBindTelephone())) {
                                return orderDetail.getBindTelephone();
                            }
                            return null;
                        })
                        .orElse(MasterPhoneUtil.getSafeMasterPhone(orderWork.getCityId()))
        );

        syncStatusData.setExtFields(JSON.toJSONString(distributeExtFields));
        syncOrderStatusDTO.setData(JSON.toJSONString(syncStatusData));
        syncOrderStatusDTO.setSign(YundingUtil.makeSign(YundingUtil.objectToMap(syncOrderStatusDTO)));

        // 发送请求
        String syncUrl = YundingConsts.API_URL + YundingConsts.SYNC_ORDER_STATUS_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,JSON.toJSONString(syncOrderStatusDTO));
        if (StringUtil.isNullOrEmpty(syncResponse)) {
            throw new OmsBaseException("发送同步派单请求失败");
        }

        log.info("【{}】同步派单，返回：【{}】",YundingConsts.CHANNEL_NAME,syncResponse);

        // 解析同步结果信息
        this.saveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_DISTRIBUTE,analysisSyncResponse(syncResponse));
    }

    /**
     * 同步师傅上门
     * @param orderWorkLogChange
     * @throws OmsBaseException
     */
    @Override
    public void syncOrderMasterVisit(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 参数验证
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("参数不能为null");
        }

        if (this.findSuccessSyncResult(orderWorkLogChange.getOrderId(),OrderStatusConsts.ORDER_STATUS_COMPLETE)) {
            throw new OmsBaseException("已同步完成，无需同步");
        }

        Long orderId = orderWorkLogChange.getOrderId();

        // 查找库或redis缓存的扩展数据
        String orderOuterData = "";
        OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);
        if(Objects.nonNull(orderExtend)) {
            orderOuterData = orderExtend.getOuterData();
        } else {
            orderOuterData = getOrderCacheData(orderId);
        }

        if (StringUtil.isNullOrEmpty(orderOuterData)) {
            throw new OmsBaseException("查找订单相关数据失败");
        }

        YundingOrderExtend yundingOrderExtend = null;
        try {
            yundingOrderExtend = JSON.parseObject(orderOuterData,YundingOrderExtend.class);
        } catch (Exception exception) {
            throw new OmsBaseException("读取工单扩展数据异常");
        }

        if (Objects.isNull(yundingOrderExtend)) {
            throw new OmsBaseException("读取工单扩展数据失败");
        }

        // 生成上门数据
        YundingSyncOrderStatusDTO syncOrderStatusDTO = newYundingSyncOrderStatusDTO();

        // 同步确认数据
        YundingSyncStatusData syncStatusData = newYundingSyncStatusData(orderWorkLogChange.getOrderId(),
                YundingConsts.ORDER_STATUS_WAITING_CONSTRUCT);

        // 师傅信息
        YundingVisitExtFields visitExtFields = new YundingVisitExtFields();
        visitExtFields.setLatitude(yundingOrderExtend.getLatitude());
        visitExtFields.setLongitude(yundingOrderExtend.getLongitude());

        syncStatusData.setExtFields(JSON.toJSONString(visitExtFields));
        syncOrderStatusDTO.setData(JSON.toJSONString(syncStatusData));
        syncOrderStatusDTO.setSign(YundingUtil.makeSign(YundingUtil.objectToMap(syncOrderStatusDTO)));

        // 发送请求
        String syncUrl = YundingConsts.API_URL + YundingConsts.SYNC_ORDER_STATUS_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,JSON.toJSONString(syncOrderStatusDTO));
        if (StringUtil.isNullOrEmpty(syncResponse)) {
            throw new OmsBaseException("发送同步上门请求失败");
        }

        log.info("【{}】同步上门，返回：【{}】",YundingConsts.CHANNEL_NAME,syncResponse);

        // 解析同步结果信息
        this.saveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_VISIT,analysisSyncResponse(syncResponse));
    }

    /**
     * 同步订单取消
     * @param orderWorkLogChange
     * @throws OmsBaseException
     */
    @Override
    public void syncOrderCancel(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 参数验证
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("参数不能为null");
        }

        // 判断是否为云丁鹿客渠道取消的订单，是则不处理
        if ((orderWorkLogChange.getOperatorId() == Long.valueOf(OrderConsts.CHANNEL_ID_YUNDING_LOCK)) &&
                (orderWorkLogChange.getOperatorType() == GlobalConsts.OPERATE_USER_TYPE_CHANNEL)) {
            throw new OmsBaseException("工单为渠道方取消，无需同步");
        }

        if (this.findSuccessSyncResult(orderWorkLogChange.getOrderId(),OrderStatusConsts.ORDER_STATUS_COMPLETE)) {
            throw new OmsBaseException("已同步完成，无需同步");
        }

        // 获取取消原因
        Long orderId = orderWorkLogChange.getOrderId();
        Long workId = orderWorkLogChange.getWorkId();
        String cancelReason = "订单被强制取消";
        OrderRemark orderRemark = orderRemarkService.findByOrderIdAndType(orderId, workId, OrderConsts.ORDER_REMARK_TYPE_CANCEL);
        if (Objects.nonNull(orderRemark)) {
            if (StringUtil.isNullOrEmpty(orderRemark.getContent())) {

                List<OrderRemarkDetail> remarkDetailList = orderRemarkDetailService.listOrderRemarkDetailByRemarkId(orderId, workId,
                        orderRemark.getRemarkId());
                if (!CollectionUtils.isEmpty(remarkDetailList)) {
                    cancelReason = remarkDetailList.get(0).getMapName();
                }
            } else {
                cancelReason = orderRemark.getContent();
            }
        }

        // 生成同步数据
        YundingSyncOrderStatusDTO syncOrderStatusDTO = newYundingSyncOrderStatusDTO();

        // 同步取消数据
        YundingSyncStatusData syncStatusData = newYundingSyncStatusData(orderWorkLogChange.getOrderId(),
                YundingConsts.ORDER_STATUS_CANCELED);

        // 取消信息
        YundingCancelExtFields cancelExtFields = new YundingCancelExtFields();
        cancelExtFields.setCancelReason(cancelReason);

        syncStatusData.setExtFields(JSON.toJSONString(cancelExtFields));
        syncOrderStatusDTO.setData(JSON.toJSONString(syncStatusData));
        syncOrderStatusDTO.setSign(YundingUtil.makeSign(YundingUtil.objectToMap(syncOrderStatusDTO)));

        // 发送请求
        String syncUrl = YundingConsts.API_URL + YundingConsts.SYNC_ORDER_STATUS_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,JSON.toJSONString(syncOrderStatusDTO));
        if (StringUtil.isNullOrEmpty(syncResponse)) {
            throw new OmsBaseException("发送同步取消订单请求失败");
        }

        log.info("【{}】同步订单取消，返回：【{}】",YundingConsts.CHANNEL_NAME,syncResponse);

        // 解析同步结果信息
        this.saveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_CANCEL,analysisSyncResponse(syncResponse));
    }

    /**
     * 同步订单服务完成
     * @param orderWorkLogChange
     * @throws OmsBaseException
     */
    @Override
    public void syncOrderServiceComplete(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 参数验证
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("参数不能为null");
        }

        // 保存服务完成
        YundingSyncResponse response = new YundingSyncResponse();
        response.setSuccess(Boolean.TRUE);
        response.setErrorMsg("Success");
        this.saveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_COMPLETE,response);
    }

    /**
     * 同步订单完成 - 空跑状态
     * @param orderWorkLogChange
     * @throws OmsBaseException
     */
    @Override
    public void syncOrderComplete(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        // 参数验证
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("参数不能为null");
        }

        // 读取工单信息
        Long orderId = orderWorkLogChange.getOrderId();
        Long workId = orderWorkLogChange.getWorkId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,workId);
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException("查找不到工单信息");
        }

        // 判断是否为空跑
        if (!Objects.equals(orderWork.getTotalAmount() ,YundingConsts.MASTER_ONLYRUN_AMOUNT)) {
            throw new OmsBaseException("不为空跑单，无需同步");
        }

        if (this.findSuccessSyncResult(orderWorkLogChange.getOrderId(),OrderStatusConsts.ORDER_STATUS_COMPLETE)) {
            throw new OmsBaseException("已同步完成，无需同步");
        }

        // 生成同步数据
        YundingSyncOrderStatusDTO syncOrderStatusDTO = newYundingSyncOrderStatusDTO();

        // 同步空跑数据
        YundingSyncStatusData syncStatusData = newYundingSyncStatusData(orderWorkLogChange.getOrderId(),
                YundingConsts.ORDER_STATUS_SERVED_NOT_INSTALL);

        // 空跑信息
        YundingUnworkExtFields unworkExtFields = new YundingUnworkExtFields();
        unworkExtFields.setReason(YundingConsts.MASTER_ONLYRUN_REASON);

        syncStatusData.setExtFields(JSON.toJSONString(unworkExtFields));
        syncOrderStatusDTO.setData(JSON.toJSONString(syncStatusData));
        syncOrderStatusDTO.setSign(YundingUtil.makeSign(YundingUtil.objectToMap(syncOrderStatusDTO)));

        // 发送请求
        String syncUrl = YundingConsts.API_URL + YundingConsts.SYNC_ORDER_STATUS_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,JSON.toJSONString(syncOrderStatusDTO));
        if (StringUtil.isNullOrEmpty(syncResponse)) {
            throw new OmsBaseException("发送同步订单空跑请求失败");
        }

        log.info("【{}】同步订单空跑，返回：【{}】",YundingConsts.CHANNEL_NAME,syncResponse);

        // 解析同步结果信息
        this.saveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_COMPLETE,analysisSyncResponse(syncResponse));
    }

    /**
     * 查找云丁渠道订单的资料 - dubbo接口实现
     *
     * @param orderId
     * @return
     * @throws OmsBaseException
     */
    @Override
    public YundingOrderCacheData getOrderShowData(Long orderId) throws OmsBaseException {

        // 判断功能是否开启
        if (!YundingConsts.POWER_ON) {
            throw new OmsBaseException(String.format("%s [H5接口读取订单资料] 暂不支持",YundingConsts.CHANNEL_NAME));
        }

        if (NumberUtil.isNullOrZero(orderId)) {
            throw new OmsBaseException("参数不能为null");
        }

        log.info("【{}】H5接口读取订单相关资料---<{}>",YundingConsts.CHANNEL_NAME,orderId);
        // 读取redis或数据库的数据
        String cacheContent = this.getOrderCacheData(orderId);
        if (StringUtil.isNullOrEmpty(cacheContent)) {

            // 从数据库读取
            OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);
            if (Objects.isNull(orderExtend)) {
                throw new OmsBaseException("读取不到对应的云丁订单资料");
            }

            cacheContent = orderExtend.getOuterData();
            if (StringUtil.isNullOrEmpty(cacheContent)) {
                throw new OmsBaseException("云丁订单资料没有保存");
            }
        }

        // JSON -> YundingOrderCacheData
        YundingOrderCacheData yundingOrderCacheData;
        try {
            yundingOrderCacheData = JSON.parseObject(cacheContent,YundingOrderCacheData.class);
        } catch (Exception e) {
            throw new OmsBaseException("读取云丁订单资料异常");
        }

        if (Objects.isNull(yundingOrderCacheData)) {
            throw new OmsBaseException("读取云丁订单资料失败");
        }

        log.info("【{}】H5接口读取订单相关资料，应答<{}>",YundingConsts.CHANNEL_NAME,JSON.toJSONString(yundingOrderCacheData));
        return yundingOrderCacheData;
    }

    /**
     * 保存填写的云丁渠道订单的相关资料 - dubbo接口实现
     *
     * @param orderId
     * @param yundingOrderCacheData
     * @throws OmsBaseException
     */
    @Override
    public void saveOrderShowData(Long orderId, YundingOrderCacheData yundingOrderCacheData) throws OmsBaseException {

        // 判断功能是否开启
        if (!YundingConsts.POWER_ON) {
            throw new OmsBaseException(String.format("%s [H5接口保存订单资料] 暂不支持",YundingConsts.CHANNEL_NAME));
        }

        if (NumberUtil.isNullOrZero(orderId) || Objects.isNull(yundingOrderCacheData)) {
            throw new OmsBaseException("参数不能为null");
        }

        log.info("【{}】H5接口保存订单相关资料，参数<{}><{}>",YundingConsts.CHANNEL_NAME,orderId,yundingOrderCacheData.toString());
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,orderId);
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException("查找不到对应的订单");
        }

        YundingOrderCacheData redisOrderCacheData = null;
        String cacheContent ;

        do {
            cacheContent = this.getOrderCacheData(orderId);
            if (!StringUtil.isNullOrEmpty(cacheContent)) {
                break;
            }

            // redis数据已经删除，从数据库读取基本数据
            OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderId);
            if (Objects.isNull(orderExtend)) {
                break;
            }

            cacheContent = orderExtend.getOuterData();
        } while(false);

        if (!StringUtil.isNullOrEmpty(cacheContent)) {
            try {
                redisOrderCacheData = JSON.parseObject(cacheContent,YundingOrderCacheData.class);
            } catch (Exception e) {
                throw new OmsBaseException("数据解析失败");
            }
        }

        String orderLog ;

        if (Objects.isNull(redisOrderCacheData)) {
            redisOrderCacheData = yundingOrderCacheData;

            // 安装单
            if (yundingOrderCacheData.getOrderInstall()) {

                StringBuilder sbOrderLog = new StringBuilder();
                sbOrderLog.append("面板SN：").append(yundingOrderCacheData.getPanelSn())
                        .append("，锁体SN：").append(yundingOrderCacheData.getLockSn());

                orderLog = sbOrderLog.toString();
            } else {    //维修单

                orderLog = this.pickOrderLogByYundingOrderData(yundingOrderCacheData);
            }

        } else {

            // 安装单
            if (redisOrderCacheData.getOrderInstall()) {

                redisOrderCacheData.setPanelSn(yundingOrderCacheData.getPanelSn());
                redisOrderCacheData.setLockSn(yundingOrderCacheData.getLockSn());

                StringBuilder sbOrderLog = new StringBuilder();
                sbOrderLog.append("面板SN：").append(redisOrderCacheData.getPanelSn())
                        .append("，锁体SN：").append(redisOrderCacheData.getLockSn());
                orderLog = sbOrderLog.toString();

            } else {    //维修单
                orderLog = this.saveInputYundingOrderData(yundingOrderCacheData,redisOrderCacheData);
            }
        }

        try {
            cacheContent = JSON.toJSONString(redisOrderCacheData);
        } catch (Exception e) {
            throw new OmsBaseException("保存失败");
        }

        log.info("【{}】填写云丁资料【{}】",YundingConsts.CHANNEL_NAME,cacheContent);
        this.saveOrderCacheData(orderId,cacheContent);
        this.saveOrderLog(orderId,orderLog,true);
    }

    /**
     * 同步旧件回寄 - dubbo接口实现
     *
     * @throws OmsBaseException
     */
    @Override
    public void syncOldPartSendBack(YundingOldPartSendbackDTO oldPartSendbackDTO) throws OmsBaseException {

        // 判断功能是否开启
        if (!YundingConsts.POWER_ON) {
            throw new OmsBaseException(String.format("%s [H5接口旧件回寄] 暂不支持",YundingConsts.CHANNEL_NAME));
        }

        log.info("【{}】H5接口旧件回寄，参数<{}>",YundingConsts.CHANNEL_NAME,oldPartSendbackDTO.toString());

        if (Objects.isNull(oldPartSendbackDTO)) {
            throw new OmsBaseException("参数不能为null");
        }

        Long orderId = Long.valueOf(oldPartSendbackDTO.getOrderNumber());
        if (NumberUtil.isNullOrZero(orderId) || StringUtil.isNullOrEmpty(oldPartSendbackDTO.getExpressCompanyName()) ||
                StringUtil.isNullOrEmpty(oldPartSendbackDTO.getExpressNumber()) ||
                StringUtil.isNullOrEmpty(oldPartSendbackDTO.getExpressPackagesPicturesUrl())) {
            throw new OmsBaseException("订单号/物流公司/物流单号/快递图片 不能为空");
        }

        // 判断订单是否需要旧件回寄
        YundingOrderCacheData redisOrderCacheData = null;
        String cacheContent = this.getOrderCacheData(orderId);

        if (!StringUtil.isNullOrEmpty(cacheContent)) {
            try {
                redisOrderCacheData = JSON.parseObject(cacheContent,YundingOrderCacheData.class);
            } catch (Exception e) {
                throw new OmsBaseException("数据解析失败");
            }
        }

        if (Objects.isNull(redisOrderCacheData)) {
            throw new OmsBaseException("服务器错误，读取数据失败");
        }

        if (Objects.isNull(redisOrderCacheData.getOldPartSendBack()) || !redisOrderCacheData.getOldPartSendBack()) {
            throw new OmsBaseException("此订单不需要旧件回寄");
        }

        // 保存到redis
        redisOrderCacheData.setExpressCompanyName(oldPartSendbackDTO.getExpressCompanyName());
        redisOrderCacheData.setExpressNumber(oldPartSendbackDTO.getExpressNumber());
        redisOrderCacheData.setExpressPackagesPicturesUrl(oldPartSendbackDTO.getExpressPackagesPicturesUrl());

        try {
            cacheContent = JSON.toJSONString(redisOrderCacheData);
            this.saveOrderCacheData(orderId,cacheContent);
        } catch (Exception e) {
            log.info("【{}】保存旧件回寄信息失败",YundingConsts.CHANNEL_NAME);
        }


        // 填入请求参数
        oldPartSendbackDTO.setAppKey(YundingConsts.APP_KEY);
        oldPartSendbackDTO.setTimestamp(DateUtil.getNowTimestampMillis());
        oldPartSendbackDTO.setSign(YundingUtil.makeSign(YundingUtil.objectToMap(oldPartSendbackDTO)));

        // 发送请求
        String syncUrl = YundingConsts.API_URL + YundingConsts.OLD_PART_SENDBACK_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,JSON.toJSONString(oldPartSendbackDTO));
        if (StringUtil.isNullOrEmpty(syncResponse)) {
            throw new OmsBaseException("发送同步订单旧件回寄请求失败");
        }

        log.info("【{}】同步旧件回寄，返回：【{}】",YundingConsts.CHANNEL_NAME,syncResponse);

        // 解析同步结果信息
        analysisSyncResponse(syncResponse);

        // 添加后台工单操作日志
        StringBuilder sbOperateLog = new StringBuilder();
        sbOperateLog.append("同步旧件回寄信息-----物流公司：").append(oldPartSendbackDTO.getExpressCompanyName())
                .append("，快递单号：").append(oldPartSendbackDTO.getExpressNumber())
                .append("，快递图片：<img src=").append(oldPartSendbackDTO.getExpressPackagesPicturesUrl()).append(">,");
        this.saveOrderLog(Long.valueOf(oldPartSendbackDTO.getOrderNumber()),sbOperateLog.toString(),true);
    }

    /**
     * 验证并同步订单完成数据
     *
     * @param orderId
     * @throws OmsBaseException
     */
    @Override
    public void verifyCompleteOrder(Long orderId, Long workId) throws OmsBaseException {

        // 判断功能是否开启
        if (!YundingConsts.POWER_ON) {
            log.info("【{}】暂不支持，不需要订单完成验证", YundingConsts.CHANNEL_NAME);
            return;
        }

        // 参数判断
        if (NumberUtil.isNullOrZero(orderId) || NumberUtil.isNullOrZero(workId)) {
            throw new OmsBaseException("参数不能为空");
        }

        if (this.findSuccessSyncResult(orderId,OrderStatusConsts.ORDER_STATUS_COMPLETE)) {
            log.info("【{}】已同步完成，不需要再次同步验证", YundingConsts.CHANNEL_NAME);
            return;
        }

        // 查找工单
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,workId);
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException("查找不到对应的工单");
        }

        if (!Objects.equals(orderWork.getInputType(),OrderConsts.ORDER_INPUT_TYPE_API)) {
            log.info("【{}】的录入方式不为API接入，不需要订单完成验证", YundingConsts.CHANNEL_NAME);
            return;
        }

        if (CollectionUtils.isEmpty(orderServiceItemService.listByOrderId(orderId))) {
            throw new OmsBaseException("订单没有选择服务项");
        }

        // 判断是否为空跑
        if ( Objects.equals(orderWork.getTotalAmount() ,YundingConsts.MASTER_ONLYRUN_AMOUNT)) {
            return;
        }

        // 读取redis缓存数据
        String completeContent = getOrderCacheData(orderId);
        if (StringUtil.isNullOrEmpty(completeContent)) {
            throw new OmsBaseException("读取填写的云丁资料失败");
        }

        // 解析JSON数据
        YundingOrderCacheData yundingOrderCacheData = null;
        try {
            yundingOrderCacheData = JSON.parseObject(completeContent, YundingOrderCacheData.class);
        } catch (Exception e) {
            throw new OmsBaseException("读取填写的云丁资料异常");
        }

        if (Objects.isNull(yundingOrderCacheData)) {
            throw new OmsBaseException("读取填写的云丁资料失败,请重新填写");
        }

        if (!checkSaveYundingData(yundingOrderCacheData)) {
            throw new OmsBaseException("云丁资料不完整,请填写");
        }
        // 转换为请求数据
        // 生成同步数据
        YundingSyncOrderStatusDTO syncOrderStatusDTO = newYundingSyncOrderStatusDTO();

        // 同步完成数据
        YundingSyncStatusData syncStatusData = newYundingSyncStatusData(orderId,YundingConsts.ORDER_STATUS_COMPLETED);

        // 完成相关填写信息
        YundingCompleteExtFields completeExtFields = new YundingCompleteExtFields();
        completeExtFields.setCompletedTime(DateUtil.getNow());

        // 读取工单照片
        String orderImageSrc = this.getOrderImageSrc(orderId);
        if (StringUtil.isNullOrEmpty(orderImageSrc)) {
            throw new OmsBaseException("没有订单照片，请提交订单照片");
        }

        // 设置完成信息中的师傅完工验收图片
        String[] orderImageList = orderImageSrc.split(",");
        completeExtFields.setAcceptPictureUrl(orderImageList[0]);
        if (orderImageList.length > 1) {
            completeExtFields.setAcceptPictureUrl2(orderImageList[1]);
        } else {
            completeExtFields.setAcceptPictureUrl2(orderImageList[0]);
        }

        if (orderImageList.length > 2) {
            completeExtFields.setAcceptPictureUrl3(orderImageList[2]);
        } else {
            completeExtFields.setAcceptPictureUrl3(orderImageList[0]);
        }

        if (orderImageList.length > 3) {
            completeExtFields.setAcceptPictureUrl4(orderImageList[3]);
        } else {
            completeExtFields.setAcceptPictureUrl4(orderImageList[0]);
        }

        // 维修工单数据
        if (orderWork.getProductId() == YundingConsts.PRODUCT_ID_REPAIR) {
            completeExtFields.setProcessMethodCode(yundingOrderCacheData.getProcessMethodCode());
            completeExtFields.setReplaceType(YundingConsts.ORDER_REPAIR_RELACE_TYPE);

            // sn码
            completeExtFields.setProductSnCodes(this.getProductSnCodes(yundingOrderCacheData,false));

            // 替换商品
            completeExtFields.setReplaceProduct(this.getReplaceProduct(yundingOrderCacheData));
        } else {
            // sn码
            completeExtFields.setProductSnCodes(this.getProductSnCodes(yundingOrderCacheData,true));
        }

        syncStatusData.setExtFields(JSON.toJSONString(completeExtFields));
        syncOrderStatusDTO.setData(JSON.toJSONString(syncStatusData));
        syncOrderStatusDTO.setSign(YundingUtil.makeSign(YundingUtil.objectToMap(syncOrderStatusDTO)));

        // 发送请求
        String syncUrl = YundingConsts.API_URL + YundingConsts.SYNC_ORDER_STATUS_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,JSON.toJSONString(syncOrderStatusDTO));
        if (StringUtil.isNullOrEmpty(syncResponse)) {
            this.saveOrderLog(orderId,"操作订单完成失败：同步云丁完成失败，失败原因：发送订单完成请求失败",false);
            throw new OmsBaseException("发送订单完成请求失败，请重试");
        }

        log.info("【{}】发送订单完成请求，返回：【{}】",YundingConsts.CHANNEL_NAME,syncResponse);
        YundingSyncResponse yundingSyncResponse = analysisSyncResponse(syncResponse);

        if (!yundingSyncResponse.getSuccess()) {
            this.saveOrderLog(orderId,String.format("操作订单完成失败：同步云丁完成失败，渠道返回失败，代码：%s，消息：%s",yundingSyncResponse.getErrorCode(),
                    yundingSyncResponse.getErrorMsg()),false);
            throw new OmsBaseException(yundingSyncResponse.getErrorMsg());
        }

        this.saveOrderLog(orderId,"同步订单完成状态：操作成功",false);
    }

    /**
     * 获取工单照片 从 oms_order_attachment + oms_order_extend 中读取
     *
     * @param orderId
     * @return
     */
    protected String getOrderImageSrc(Long orderId) {

        StringBuilder imageSrc = new StringBuilder();

        // 读取 oms_order_attachment 的工单照片
        List<OrderAttachment> orderAttachments = orderAttachmentService.listAttachmentByOrderId(orderId);
        if (!CollectionUtils.isEmpty(orderAttachments)) {
            for (OrderAttachment orderAttachment : orderAttachments) {
                if (!StringUtil.isNullOrEmpty(orderAttachment.getSrc())) {
                    imageSrc.append(orderAttachment.getSrc()).append(",");
                }
            }
        }

        // 读取 oms_order_extend 的工单照片
        OrderExtend orderExtend = orderExtendService.findMiniOrderExtendByOrderId(orderId);
        if (Objects.nonNull(orderExtend) && !StringUtil.isNullOrEmpty(orderExtend.getImageSrc())) {
            imageSrc.append(orderExtend.getImageSrc());
        }

        return imageSrc.toString();
    }

    /**
     * 检查保存的云丁资料是否完整
     *
     * @param yundingOrderData
     * @return
     */
    private boolean checkSaveYundingData(YundingOrderCacheData yundingOrderData) {

        if (Objects.isNull(yundingOrderData)) {
            return false;
        }

        // 安装单
        if (yundingOrderData.getOrderInstall()) {

            // 面板SN 和 锁体SN
            if (StringUtil.isNullOrEmpty(yundingOrderData.getPanelSn()) ||
                    StringUtil.isNullOrEmpty(yundingOrderData.getLockSn())) {
                return false;
            }

            return true;
        }

        // 维修单
        // 解决方法
        if (StringUtil.isNullOrEmpty(yundingOrderData.getProcessMethodCode())) {
            return false;
        }

        // sn 和 替换商品
        switch (yundingOrderData.getProcessMethodCode()) {

            case YundingConsts.PROCESS_METHOD_REPLACE_WHOLE_LOCK:
            case YundingConsts.PROCESS_METHOD_PRODUCT_UPGRADES:

                // sn 码
                if (StringUtil.isNullOrEmpty(yundingOrderData.getPanelSn()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getLockSn()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getOldLockSn()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getOldPanelSn())) {
                    return false;
                }

                // 替换商品
                if (StringUtil.isNullOrEmpty(yundingOrderData.getPanelSku()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getLockSku()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getSliderSku())) {
                    return false;
                }

                break;
            case YundingConsts.PROCESS_METHOD_VISIT_DEBUG:
                break;

            case YundingConsts.PROCESS_METHOD_REPLACE_FACEPLATE:

                // SN码 和替 换商品
                if (StringUtil.isNullOrEmpty(yundingOrderData.getPanelSn()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getOldPanelSn()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getPanelSku())) {
                    return false;
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_LOCK_BODY:

                // SN码 和替 换商品
                if (StringUtil.isNullOrEmpty(yundingOrderData.getLockSn()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getOldLockSn()) ||
                        StringUtil.isNullOrEmpty(yundingOrderData.getLockSku())) {
                    return false;
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_SIDE_BAR:

                // 侧条替换商品
                if (StringUtil.isNullOrEmpty(yundingOrderData.getSliderSku())) {
                    return false;
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_LOCK_CORE:

                // 锁芯替换商品
                if (StringUtil.isNullOrEmpty(yundingOrderData.getLockCylinderSku())) {
                    return false;
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_FINGERPRINT_HEAD:

                // 指纹头替换商品
                if (StringUtil.isNullOrEmpty(yundingOrderData.getFigptHeadSku())) {
                    return false;
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_GATEWAY:
              // 网关替换商品
                if (StringUtil.isNullOrEmpty(yundingOrderData.getGateWaySku())) {
                    return false;
                }
                break;
        }

        return true;
    }
    
    /**
     * 查询状态同步结果信息
     *
     * @param orderId
     * @param orderStatus
     * @return boolean
     */
    private Boolean findSuccessSyncResult(Long orderId, int orderStatus) {

        if (NumberUtil.isNullOrZero(orderId)) {
            return Boolean.FALSE;
        }

        List<OrderNotifyLog> orderNotifyLogs = orderNotifyLogBService.listByOrderId(orderId);
        if (Objects.isNull(orderNotifyLogs)) {
            return Boolean.FALSE;
        }

        for (OrderNotifyLog item : orderNotifyLogs) {
            if (Objects.equals(String.valueOf(orderStatus), item.getNotifyStatus())
                    && Objects.equals(StatusConsts.STATUS_SUCCESS, item.getNotifyResultStatus())) {
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }

    /**
     * 生成同步订单状态的基础数据
     *
     * @return
     */
    private YundingSyncOrderStatusDTO newYundingSyncOrderStatusDTO() {

        YundingSyncOrderStatusDTO syncOrderStatusDTO = new YundingSyncOrderStatusDTO();
        syncOrderStatusDTO.setAppKey(YundingConsts.APP_KEY);
        syncOrderStatusDTO.setTimestamp(DateUtil.getNowTimestampMillis());
        syncOrderStatusDTO.setType(YundingConsts.TYPE_ORDER_STATUS);

        return syncOrderStatusDTO;
    }

    /**
     * 生成同步订单状态的数据
     *
     * @return
     */
    private YundingSyncStatusData newYundingSyncStatusData(Long orderId, String statusCode) {

        YundingSyncStatusData syncStatusData = new YundingSyncStatusData();
        syncStatusData.setOrderNumber(String.valueOf(orderId));
        syncStatusData.setStatusCode(statusCode);
        syncStatusData.setStatusName(YundingConsts.getStatusName(statusCode));

        return syncStatusData;
    }

    /**
     * 退同步请求返回数据进行解析
     *
     * @param response
     * @throws OmsBaseException
     */
    private YundingSyncResponse analysisSyncResponse(String response) throws OmsBaseException {

        // 解析返回的JSON数据
        try {
            YundingSyncResponse yundingSyncResponse = JSON.parseObject(response,YundingSyncResponse.class);
            if (Objects.isNull(yundingSyncResponse)) {
                throw new OmsBaseException("解析同步请求返回数据失败");
            }

            return yundingSyncResponse;
        } catch (Exception e) {
            throw new OmsBaseException("解析同步请求返回数据异常");
        }
    }

    /**
     * 保存状态同步结果信息
     *
     * @param orderWorkLogChange
     * @param orderStatus
     * @param result
     */
    @SuppressWarnings("all")
    private void saveSyncResult(OrderWorkLogChange orderWorkLogChange, int orderStatus, YundingSyncResponse response) {
        if (Objects.isNull(response) || Objects.isNull(orderWorkLogChange)) {
            return;
        }

        OrderNotifyLog orderNotifyLog = new OrderNotifyLog();
        orderNotifyLog.setMqMsgKey(orderWorkLogChange.getMqMsgKey());
        orderNotifyLog.setOrderId(orderWorkLogChange.getOrderId());
        orderNotifyLog.setChannelId(orderWorkLogChange.getChannelId());
        orderNotifyLog.setOrderStatus(orderWorkLogChange.getStatus());
        orderNotifyLog.setOrderResultStatus(orderWorkLogChange.getResultStatus());
        orderNotifyLog.setNotifyStatus(String.valueOf(orderStatus));
        orderNotifyLog.setType(OrderConsts.ORDER_NOTIFY_TYPE_CHANGE);
        orderNotifyLog.setNotifyTime(DateUtil.getNow());
        orderNotifyLog.setNotifyResultMsg(String.format("[%s]-%s",
                OrderStatusConsts.getOrderStatusName(orderStatus), response.getErrorMsg()));

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setStatus(response.getSuccess() ? StatusConsts.STATUS_SUCCESS : StatusConsts.STATUS_ERROR);
        resultDTO.setData(orderNotifyLog);

        orderNotifyLogBService.saveNotifyLog(resultDTO);
    }

    /**
     * 生成商品 sn 码(如商品有 sn 码 ，则会返回该值)（多个，中间逗号分隔）
     *
     * @param orderCacheData
     * @return
     */
    private String getProductSnCodes(YundingOrderCacheData orderCacheData,boolean isInstall) {

        if (Objects.isNull(orderCacheData)) {
            return "";
        }

        // 面板sn
        StringBuilder sbSnCodes = new StringBuilder();

        // 安装单
        if (isInstall) {

            sbSnCodes.append(Optional.ofNullable(orderCacheData.getPanelSn()).orElse("")).append(",");
            sbSnCodes.append(Optional.ofNullable(orderCacheData.getLockSn()).orElse(""));

            return sbSnCodes.toString();
        }

        if (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_VISIT_DEBUG) == 0 ||
                orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_SIDE_BAR) == 0 ||
                orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_LOCK_CORE) == 0 ||
                orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_FINGERPRINT_HEAD) == 0 ||
                orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_GATEWAY) == 0 ) {
            return "";
        }

        sbSnCodes.append(Optional.ofNullable(orderCacheData.getPanelSn()).orElse("")).append(",");
        sbSnCodes.append(Optional.ofNullable(orderCacheData.getLockSn()).orElse("")).append(",");
        sbSnCodes.append(Optional.ofNullable(orderCacheData.getOldPanelSn()).orElse("")).append(",");
        sbSnCodes.append(Optional.ofNullable(orderCacheData.getOldLockSn()).orElse(""));

        return sbSnCodes.toString();
    }

    /**
     * 生成完成信息里面的替换商品(sku,sku....)
     *
     * @param orderCacheData
     * @return
     */
    private String getReplaceProduct(YundingOrderCacheData orderCacheData) {

        if (Objects.isNull(orderCacheData)) {
            return null;
        }

        StringBuilder sbProductSku = new StringBuilder();

        // 维修单 - 面板
        boolean needPannel = (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_PRODUCT_UPGRADES) == 0) ||
                (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_WHOLE_LOCK) == 0) ||
                (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_FACEPLATE) == 0);
        // 面板sku
        if (!StringUtil.isNullOrEmpty(orderCacheData.getPanelSku()) && needPannel) {
            sbProductSku.append(orderCacheData.getPanelSku()).append(",");
        }

        boolean needLockBody = (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_PRODUCT_UPGRADES) == 0) ||
                (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_WHOLE_LOCK) == 0) ||
                (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_LOCK_BODY) == 0);
        // 锁体sku
        if (!StringUtil.isNullOrEmpty(orderCacheData.getLockSku()) && needLockBody) {
            sbProductSku.append(orderCacheData.getLockSku()).append(",");
        }

        boolean needSlider = (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_PRODUCT_UPGRADES) == 0) ||
                (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_WHOLE_LOCK) == 0) ||
                (orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_SIDE_BAR) == 0);
        // 侧条sku
        if (!StringUtil.isNullOrEmpty(orderCacheData.getSliderSku()) && needSlider) {
            sbProductSku.append(orderCacheData.getSliderSku()).append(",");
        }

        // 指纹头
        if ((orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_FINGERPRINT_HEAD) == 0) &&
                !StringUtil.isNullOrEmpty(orderCacheData.getFigptHeadSku())) {
            sbProductSku.append(orderCacheData.getFigptHeadSku()).append(",");
        }

        // 锁芯
        if ((orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_LOCK_CORE) == 0) &&
                !StringUtil.isNullOrEmpty(orderCacheData.getLockCylinderSku())) {
            sbProductSku.append(orderCacheData.getLockCylinderSku()).append(",");
        }

        // 网关
        if ((orderCacheData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_REPLACE_GATEWAY) == 0) &&
                !StringUtil.isNullOrEmpty(orderCacheData.getGateWaySku())) {
            sbProductSku.append(orderCacheData.getGateWaySku()).append(",");
        }

        if (sbProductSku.length() > 0) {
            sbProductSku.deleteCharAt(sbProductSku.length() - 1);
        }
        return sbProductSku.toString();
    }

    /**
     * 读取保存在redis的工单信息
     *
     * @param orderId
     * @return
     */
    private String getOrderCacheData(Long orderId) {

        if (NumberUtil.isNullOrZero(orderId)) {
            return "";
        }

        String redisKey = String.format(RedisKeyConsts.YUNDING_LOCK_DATA_REDIS_KEY,orderId);
        return redisManager.get(redisKey);
    }

    /**
     * 保存工单信息到redis缓存
     *
     * @param orderId
     * @param orderCacheData
     * @return
     */
    private void saveOrderCacheData(Long orderId, String orderCacheData) {

        if (NumberUtil.isNullOrZero(orderId) || StringUtil.isNullOrEmpty(orderCacheData)) {
            return;
        }

        String redisKey = String.format(RedisKeyConsts.YUNDING_LOCK_DATA_REDIS_KEY,orderId);
        redisManager.setex(redisKey,orderCacheData,YundingConsts.REDIS_CACHE_TIMEOUT);

        return;
    }

    /**
     * 将云丁鹿客的订单数据转为zmn订单信息
     *
     * @param yundingCreateOrderDTO
     * @return
     */
    private FactoryNewOrderDTO buildCreateOrder(YundingCreateOrderDTO yundingCreateOrderDTO) {

        if (Objects.isNull(yundingCreateOrderDTO)) {
            return null;
        }

        String outerId = yundingCreateOrderDTO.getOrderNumber();

        // 校验是不是重复的订单消息
        ZsOrderWorkVO orderWork = zsOrderWorkQueryBService.findOrderWorkByOuterId(outerId, OrderConsts.CHANNEL_ID_YUNDING_LOCK);
        if (orderWork != null) {
            log.info("【{}】重复的订单消息数据（已忽略） OuterId:[{}]", YundingConsts.CHANNEL_NAME, outerId);
            return null;
        }

        FactoryNewOrderDTO factoryNewOrderDTO = new FactoryNewOrderDTO();

        // 渠道id
        factoryNewOrderDTO.setOuterId(outerId);

        // 订单类型
        factoryNewOrderDTO.setType(OrderConsts.ORDER_TYPE_NEW);

        // 录入类型
        factoryNewOrderDTO.setInputType(OrderConsts.ORDER_INPUT_TYPE_API);

        // 操作者
        factoryNewOrderDTO.setOperator("系统");

        // 备注
        factoryNewOrderDTO.setRemark(Optional.ofNullable(yundingCreateOrderDTO.getNote()).orElse(""));

        // 操作者id
        factoryNewOrderDTO.setOperatorId((long)OrderConsts.CHANNEL_ID_YUNDING_LOCK);

        // 操作者类型
        factoryNewOrderDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_CHANNEL);

        // 平台标志
        factoryNewOrderDTO.setPlat(GlobalConsts.PLAT_MARK_YEYX);

        // 下单入口
        factoryNewOrderDTO.setReceiveEntranceId(GateTypeConsts.GATE_API_CUSTOM_MADE);

        // 下单方式
        factoryNewOrderDTO.setReceiverManner(OrderConsts.RECEIVE_MANNER_API);

        // 联系人
        factoryNewOrderDTO.setUserName(yundingCreateOrderDTO.getCustomerName());

        // 性别
        factoryNewOrderDTO.setGender(GlobalDict.GENDER_NO);

        // 电话
        factoryNewOrderDTO.setTelephone(yundingCreateOrderDTO.getCustomerPhoneNumber());

        // 地址
        factoryNewOrderDTO.setAddress(yundingCreateOrderDTO.getDetailAddress());

        // 街道
        factoryNewOrderDTO.setStreet(Optional.ofNullable(yundingCreateOrderDTO.getDetailAddress()).orElse(""));

        // 预约时间
        factoryNewOrderDTO.setDutyTime(null);

        // 保内
        factoryNewOrderDTO.setBizType(com.zmn.consts.GlobalConsts.BIZ_TYPE_F);

        // 厂商信息
        OrderFactoryDTO orderFactory = new OrderFactoryDTO();

        // 厂商id
        // 调用异常，先采用使用常量的方式设定厂商id
        // orderFactory.setFactoryId(YundingConsts.FACTORY_ID);

 /*       ResponseDTO<FactoryBaseDRO> factoryResponseDTO; todo ligang 20220510 为什么要查一次
        try {
            factoryResponseDTO = factoryListRemoteService.getFactoryByChannelId(OrderConsts.CHANNEL_ID_YUNDING_LOCK);
        } catch (Exception e) {
            log.info("【{}】查找厂商信息失败，【{}】", YundingConsts.CHANNEL_NAME,e);
            return null;
        }

        if (!factoryResponseDTO.isSuccess() || factoryResponseDTO.getData() == null) {
            log.info("【{}】渠道ID有误，未找到对应厂商！", YundingConsts.CHANNEL_NAME);
            return null;
        }

        orderFactory.setFactoryId(factoryResponseDTO.getData().getFcId());*/

        // 厂商产品id
        orderFactory.setFcProductId(0);

        // 产品 id 和 产品数量
        YundingOrderProduct yundingOrderProduct = null;
        try {
            // 解析产品列表信息
            List<YundingOrderProduct> yundingOrderProductList = JSON.parseArray(yundingCreateOrderDTO.getOrderProducts(),YundingOrderProduct.class);
            if (!CollectionUtils.isEmpty(yundingOrderProductList)) {
                yundingOrderProduct = yundingOrderProductList.get(0);
            }
        } catch (Exception e) {

            log.info("【{}】解析商品信息异常，商品信息【{}】", YundingConsts.CHANNEL_NAME, yundingCreateOrderDTO.getOrderProducts());
            return null;
        }

        if(Objects.isNull(yundingOrderProduct)) {
            log.info("【{}】解析商品信息失败，商品信息【{}】", YundingConsts.CHANNEL_NAME, yundingCreateOrderDTO.getOrderProducts());
            return null;
        }

        orderFactory.setProductId(YundingConsts.getProductIdByServiceCode(yundingOrderProduct.getServingTypeCode()));

        // 产品数量
        orderFactory.setFcProductNumber(yundingOrderProduct.getNumber());

        // 厂商信息
        factoryNewOrderDTO.setOrderFactory(orderFactory);

        // 地址
        factoryNewOrderDTO.setAddress(yundingCreateOrderDTO.getDetailAddress());
        factoryNewOrderDTO.setStreet(yundingCreateOrderDTO.getDetailAddress());

        // 日志
        StringBuilder sbRemark = new StringBuilder();

        // 城市id
        Integer cityId = 500100;
        do {
            ResponseDTO<AreaDRO> areaResponse = null;
            boolean isCity = false;
            if (Objects.nonNull(yundingCreateOrderDTO.getLatitude()) && Objects.nonNull(yundingCreateOrderDTO.getLongitude())) {

                // 高德经纬度读取地址信息
                double[] bdLatLng = YundingUtil.gaodeToBaidu(yundingCreateOrderDTO.getLatitude().doubleValue(),yundingCreateOrderDTO.getLongitude().doubleValue());
                factoryNewOrderDTO.setLatitude(bdLatLng[0]);
                factoryNewOrderDTO.setLongitude(bdLatLng[1]);
				areaResponse = areaListRemoteService.getAreaByLatAndLng(bdLatLng[1],bdLatLng[0]);

            } else if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getDetailAddress())) {

                // 详细地址获取经纬度
                LngLatLocation areaLocation = baiduMapBService.location(yundingCreateOrderDTO.getDetailAddress());
                if (Objects.isNull(areaLocation)) {
                    break;
                }

                factoryNewOrderDTO.setLatitude(Double.valueOf(areaLocation.getLat()));
                factoryNewOrderDTO.setLongitude(Double.valueOf(areaLocation.getLng()));

                // 经纬度查找区域信息
                areaResponse = areaListRemoteService.getAreaByLatAndLng(Double.valueOf(areaLocation.getLng()), Double.valueOf(areaLocation.getLat()));
            } else if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getCityCode())){

                // 行政区码读取地址信息
                areaResponse = areaListRemoteService.getAreaByCode(Integer.valueOf(yundingCreateOrderDTO.getCityCode()));
                isCity = true;
            } else {
                break;
            }

            if (Objects.isNull(areaResponse) || Objects.isNull(areaResponse.getData())) {
                break;
            }

            cityId = Integer.valueOf(isCity ? areaResponse.getData().getAreaId() : areaResponse.getData().getParentId());

            // 再设一次经纬度
            Double longitude = Double.valueOf(areaResponse.getData().getLongitude());
            Double latitude = Double.valueOf(areaResponse.getData().getLatitude());
            factoryNewOrderDTO.setLongitude(longitude);
            factoryNewOrderDTO.setLatitude(latitude);

            /* 已有地址信息，去掉
            sbRemark.append("地址信息：省[").append(areaResponse.getData().getProvinceName()).append("],")
                    .append("市[").append(areaResponse.getData().getCityName()).append("],")
                    .append("区[").append(areaResponse.getData().getCountyName()).append("],")
                    .append(yundingCreateOrderDTO.getDetailAddress()).append(";");
             */
        } while (false);

        factoryNewOrderDTO.setCityId(cityId);

        sbRemark.append("<br>用户期望服务日期：").append(Optional.ofNullable(yundingCreateOrderDTO.getExpectServiceDate()).orElse("无"));
        if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getEnvPicUrl1()) || !StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getEnvPicUrl2()) ||
                !StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getEnvPicUrl3())) {
            sbRemark.append("<br>用户服务环境图片：");

            if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getEnvPicUrl1())) {
                sbRemark.append("<img src=").append(yundingCreateOrderDTO.getEnvPicUrl1()).append(">,");
            }

            if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getEnvPicUrl2())) {
                sbRemark.append("<img src=").append(yundingCreateOrderDTO.getEnvPicUrl2()).append(">,");
            }

            if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getEnvPicUrl3())) {
                sbRemark.append("<img src=").append(yundingCreateOrderDTO.getEnvPicUrl3()).append(">,");
            }
        }

        // 暂时去掉
        // sbRemark.append("商品信息：").append(yundingCreateOrderDTO.getOrderProducts()).append(";");

        if (orderFactory.getProductId() != YundingConsts.PRODUCT_ID_INSTALL) {

            boolean urgent = Optional.ofNullable(yundingCreateOrderDTO.getUrgentMaintain()).orElse("").compareTo("Y") == 0;
            boolean sparePartsSendback = Optional.ofNullable(yundingCreateOrderDTO.getSparePartsSendBack()).orElse("").compareTo("Y") == 0;
            boolean oldPartSendback = Optional.ofNullable(yundingCreateOrderDTO.getOldPartSendBack()).orElse("").compareTo("Y") == 0;

            sbRemark.append("<br>紧急工单：").append(urgent ? "是；" : "否；")
                    .append("<br>旧件回寄：").append(oldPartSendback ? "是；" : "否；")
                    .append("<br>备件寄回：").append(sparePartsSendback ? "是；" : "否；");


            if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getSparePartsList())) {
                sbRemark.append("<br>备件列表：").append(yundingCreateOrderDTO.getSparePartsList()).append("；");
            }

            if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getSendBackAddress())) {
                sbRemark.append("<br>旧件回寄地址：").append(yundingCreateOrderDTO.getSendBackAddress()).append("；");
            }

            if (StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getProcessMethodName())) {
                sbRemark.append("<br>建议处理方法：").append(yundingCreateOrderDTO.getProcessMethodName());
            }
        }

        factoryNewOrderDTO.setOperatorLogRemark(sbRemark.toString());

        return factoryNewOrderDTO;

        /*
        CreateOrderDTO createOrderDTO = new CreateOrderDTO();

        // 订单类型
        createOrderDTO.setType(OrderConsts.ORDER_TYPE_NEW);

        // 渠道id
        createOrderDTO.setChannelId(OrderConsts.CHANNEL_ID_YUNDING_LOCK);

        // 外部订单id
        createOrderDTO.setThirdOrderId(outerId);

        // 联系人
        createOrderDTO.setContactName(yundingCreateOrderDTO.getCustomerName());

        // 联系人电话
        createOrderDTO.setTelephone(yundingCreateOrderDTO.getCustomerPhoneNumber());

        // 性别
        createOrderDTO.setGender(GlobalDict.GENDER_NO);

        // 预约时间
        createOrderDTO.setDutyTime(null);

        // 厂商单
        createOrderDTO.setFactory(GlobalConsts.YES);

        // 保内
        createOrderDTO.setFacInWarranty(GlobalConsts.YES);

        // 产品
        YundingOrderProduct yundingOrderProduct = null;
        try {
            // 解析产品列表信息
            List<YundingOrderProduct> yundingOrderProductList = JSON.parseArray(yundingCreateOrderDTO.getOrderProducts(),YundingOrderProduct.class);
            if (!CollectionUtils.isEmpty(yundingOrderProductList)) {
                yundingOrderProduct = yundingOrderProductList.get(0);
            }
        } catch (Exception e) {

            log.info("【{}】解析商品信息异常，商品信息【{}】", YundingConsts.CHANNEL_NAME, yundingCreateOrderDTO.getOrderProducts());
            return null;
        }

        if(Objects.isNull(yundingOrderProduct)) {
            log.info("【{}】解析商品信息失败，商品信息【{}】", YundingConsts.CHANNEL_NAME, yundingCreateOrderDTO.getOrderProducts());
            return null;
        }

        createOrderDTO.setProductId(YundingConsts.getProductIdByServiceCode(yundingOrderProduct.getServingTypeCode()));

        // 产品数量
        createOrderDTO.setProductCount(yundingOrderProduct.getNumber());

        // 地址
        createOrderDTO.setAddress(yundingCreateOrderDTO.getDetailAddress());
        createOrderDTO.setStreet(yundingCreateOrderDTO.getDetailAddress());

        Integer cityId = 500100;
        do {

            com.zmn.baidumap.dto2.ResponseDTO<com.zmn.plat.baidumap.dto.area.AreaDRO> areaResponse = null;
            if (Objects.nonNull(yundingCreateOrderDTO.getLatitude()) && Objects.nonNull(yundingCreateOrderDTO.getLongitude())) {

                // 高德经纬度读取地址信息
                double[] bdLatLng = YundingUtil.gaodeToBaidu(yundingCreateOrderDTO.getLatitude().doubleValue(),yundingCreateOrderDTO.getLongitude().doubleValue());
                createOrderDTO.setLatitude(bdLatLng[0]);
                createOrderDTO.setLongitude(bdLatLng[1]);
                areaResponse = areaListRemoteService.getByLatAndLng(bdLatLng[0],bdLatLng[1]);

            } else if (Objects.nonNull(yundingCreateOrderDTO.getDistrictCode())){

                // 行政区码读取地址信息
                areaResponse = areaListRemoteService.getByCode(Integer.valueOf(yundingCreateOrderDTO.getDistrictCode()));
            } else {
                break;
            }

            if (Objects.isNull(areaResponse) || Objects.isNull(areaResponse.getData())) {
                break;
            }
            cityId = Integer.valueOf(areaResponse.getData().getParentId());

            // 再设一次经纬度
            Double longitude = Double.valueOf(areaResponse.getData().getLongitude());
            Double latitude = Double.valueOf(areaResponse.getData().getLatitude());
            createOrderDTO.setLongitude(longitude);
            createOrderDTO.setLatitude(latitude);
        } while (false);

        createOrderDTO.setCityId(cityId);

        // 日志
        StringBuilder sbRemark = new StringBuilder();
        sbRemark.append("地址信息：省[").append(yundingCreateOrderDTO.getProvinceCode()).append("],")
                .append("市[").append(yundingCreateOrderDTO.getCityCode()).append("],")
                .append("区[").append(yundingCreateOrderDTO.getDistrictCode()).append("],")
                .append(yundingCreateOrderDTO.getDetailAddress()).append(";")
                .append("用户期望服务日期：").append(yundingCreateOrderDTO.getExpectServiceDate())
                .append("用户服务环境图片：").append(yundingCreateOrderDTO.getEnvPicUrl1()).append(",")
                .append(yundingCreateOrderDTO.getEnvPicUrl2()).append(",")
                .append(yundingCreateOrderDTO.getEnvPicUrl3()).append(";")
                .append("商品信息：").append(yundingCreateOrderDTO.getOrderProducts()).append(";");

        if (createOrderDTO.getProductId() != YundingConsts.PRODUCT_ID_INSTALL) {

            boolean urgent = Optional.ofNullable(yundingCreateOrderDTO.getUrgentMaintain()).orElse("").compareTo("Y") == 0;
            boolean sendback = Optional.ofNullable(yundingCreateOrderDTO.getSparePartsSendBack()).orElse("").compareTo("Y") == 0;

            sbRemark.append("紧急工单：").append(urgent ? "是；" : "否；")
                    .append("备件寄回：").append(sendback ? "是；" : "否；")
                    .append("备件列表：").append(yundingCreateOrderDTO.getSparePartsList()).append("；")
                    .append("建议处理方法：").append(yundingCreateOrderDTO.getProcessMethodName());
        }

        createOrderDTO.setRemark(sbRemark.toString());

        // 扩展信息
        YundingOrderExtend yundingOrderExtend = buildYundingOrderExtend(yundingCreateOrderDTO);
        createOrderDTO.setOuterJsonData(JSON.toJSONString(yundingOrderExtend));

        return createOrderDTO;
        */
    }

    /**
     * YundingCreateOrderDTO部分信息转YundingOrderExtend
     *
     * @param yundingCreateOrderDTO
     * @return
     */
    private YundingOrderExtend buildYundingOrderExtend(YundingCreateOrderDTO yundingCreateOrderDTO) {

        if (Objects.isNull(yundingCreateOrderDTO)) {
            return null;
        }

        // 转换数据
        YundingOrderExtend yundingOrderExtend = new YundingOrderExtend();
        yundingOrderExtend.setOrderNumber(yundingCreateOrderDTO.getOrderNumber());
        yundingOrderExtend.setEnvPicUrl1(yundingCreateOrderDTO.getEnvPicUrl1());
        yundingOrderExtend.setEnvPicUrl2(yundingCreateOrderDTO.getEnvPicUrl2());
        yundingOrderExtend.setEnvPicUrl3(yundingCreateOrderDTO.getEnvPicUrl3());
        yundingOrderExtend.setLatitude(yundingCreateOrderDTO.getLatitude());
        yundingOrderExtend.setLongitude(yundingCreateOrderDTO.getLongitude());

        if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getUrgentMaintain())) {
            yundingOrderExtend.setUrgentMaintain(yundingCreateOrderDTO.getUrgentMaintain().compareTo("Y")==0 ? Boolean.TRUE:Boolean.FALSE);
        }

        if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getSparePartsSendBack())) {
            yundingOrderExtend.setSparePartsSendBack(yundingCreateOrderDTO.getSparePartsSendBack().compareTo("Y") == 0 ? Boolean.TRUE : Boolean.FALSE);
        }

        if (!StringUtil.isNullOrEmpty(yundingCreateOrderDTO.getOldPartSendBack())) {
            yundingOrderExtend.setOldPartSendBack(yundingCreateOrderDTO.getOldPartSendBack().compareTo("Y")==0 ? Boolean.TRUE:Boolean.FALSE);
        }

        yundingOrderExtend.setSendBackAddress(yundingCreateOrderDTO.getSendBackAddress());
        yundingOrderExtend.setSparePartsSendBackList(JSON.parseArray(yundingCreateOrderDTO.getSparePartsList(),YundingSpareParts.class));
        yundingOrderExtend.setRecommendProcessMethodCode(yundingCreateOrderDTO.getProcessMethodCode());
        yundingOrderExtend.setProcessMethodCode(yundingCreateOrderDTO.getProcessMethodCode());
        yundingOrderExtend.setProcessMethodName(yundingCreateOrderDTO.getProcessMethodName());

        return yundingOrderExtend;
    }

    /**
     * 将填写的云丁资料保存
     *
     * @param newOrderData
     * @param dbOrderData
     */
    private String saveInputYundingOrderData(YundingOrderCacheData newOrderData, YundingOrderCacheData dbOrderData) {

        boolean processChange = true;
        boolean resetData = true;
        String newProcessMethodName =  YundingConsts.getProcessMethodName(newOrderData.getProcessMethodCode());

        StringBuilder sbOrderLog = new StringBuilder();
        sbOrderLog.append("解决方案：");

        if (Objects.nonNull(dbOrderData.getProcessMethodCode()) &&
                dbOrderData.getProcessMethodCode().compareTo(newOrderData.getProcessMethodCode()) == 0) {
            processChange = false;
        }

        // 解决方案
        if (processChange) {
            sbOrderLog.append(YundingConsts.getProcessMethodName(dbOrderData.getProcessMethodCode()))
                    .append("->").append(newProcessMethodName).append(";");
        } else {
            sbOrderLog.append(newProcessMethodName).append(";");
            if ( newOrderData.getProcessMethodCode().compareTo(YundingConsts.PROCESS_METHOD_VISIT_DEBUG) != 0) {
                resetData = false;
            }
        }

        // 解决方法修改或解决方法为上门调试,sn和替换商品全部重置
        if ( resetData ) {

            // sn重置
            dbOrderData.setPanelSn(null);
            dbOrderData.setOldPanelSn(null);
            dbOrderData.setLockSn(null);
            dbOrderData.setOldLockSn(null);

            // 替换商品重置
            dbOrderData.setPanelSku(null);
            dbOrderData.setPanelName(null);
            dbOrderData.setLockSku(null);
            dbOrderData.setLockName(null);
            dbOrderData.setSliderSku(null);
            dbOrderData.setSliderName(null);
            dbOrderData.setLockCylinderSku(null);
            dbOrderData.setLockCylinderName(null);
            dbOrderData.setFigptHeadSku(null);
            dbOrderData.setFigptHeadName(null);
            dbOrderData.setGateWaySku(null);
            dbOrderData.setGateWayName(null);
        }

        dbOrderData.setProcessMethodCode(newOrderData.getProcessMethodCode());
        dbOrderData.setProcessMethodName(newProcessMethodName);

        sbOrderLog.append("<br>");
        // sn 码
        switch (dbOrderData.getProcessMethodCode()) {

            case YundingConsts.PROCESS_METHOD_REPLACE_WHOLE_LOCK:
            case YundingConsts.PROCESS_METHOD_PRODUCT_UPGRADES:

                sbOrderLog.append("面板/锁体SN信息：<br>");

                buildPartChangeLog(sbOrderLog,"  新面板SN：",newOrderData.getPanelSn(),dbOrderData.getPanelSn());
                buildPartChangeLog(sbOrderLog,"  旧面板SN：",newOrderData.getOldPanelSn(),dbOrderData.getOldPanelSn());
                buildPartChangeLog(sbOrderLog,"  新锁体SN：",newOrderData.getLockSn(),dbOrderData.getLockSn());
                buildPartChangeLog(sbOrderLog,"  旧锁体SN：",newOrderData.getOldLockSn(),dbOrderData.getOldLockSn());

                if (!StringUtil.isNullOrEmpty(newOrderData.getPanelSn())) {
                    dbOrderData.setPanelSn(newOrderData.getPanelSn());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getOldPanelSn())) {
                    dbOrderData.setOldPanelSn(newOrderData.getOldPanelSn());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getLockSn())) {
                    dbOrderData.setLockSn(newOrderData.getLockSn());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getOldLockSn())) {
                    dbOrderData.setOldLockSn(newOrderData.getOldLockSn());
                }

                sbOrderLog.append("替换商品信息：<br>");

                buildPartChangeLog(sbOrderLog,"  面板名称：",newOrderData.getPanelName(),dbOrderData.getPanelName());
                buildPartChangeLog(sbOrderLog,"  面板Sku：",newOrderData.getPanelSku(),dbOrderData.getPanelSku());

                // 面板替换商品
                if (!StringUtil.isNullOrEmpty(newOrderData.getPanelSku())) {
                    dbOrderData.setPanelSku(newOrderData.getPanelSku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getPanelName())) {
                    dbOrderData.setPanelName(newOrderData.getPanelName());
                }

                // 锁体替换商品
                buildPartChangeLog(sbOrderLog,"  锁体名称：",newOrderData.getLockName(),dbOrderData.getLockName());
                buildPartChangeLog(sbOrderLog,"  锁体sku：",newOrderData.getLockSku(),dbOrderData.getLockSku());

                if (!StringUtil.isNullOrEmpty(newOrderData.getLockSku())) {
                    dbOrderData.setLockSku(newOrderData.getLockSku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getLockName())) {
                    dbOrderData.setLockName(newOrderData.getLockName());
                }

                // 侧条替换商品
                buildPartChangeLog(sbOrderLog,"  侧条名称：",newOrderData.getSliderName(),dbOrderData.getSliderName());
                buildPartChangeLog(sbOrderLog,"  侧条Sku：",newOrderData.getSliderSku(),dbOrderData.getSliderSku());

                if (!StringUtil.isNullOrEmpty(newOrderData.getSliderSku())) {
                    dbOrderData.setSliderSku(newOrderData.getSliderSku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getSliderName())) {
                    dbOrderData.setSliderName(newOrderData.getSliderName());
                }

                sbOrderLog.append("；");

                break;
            case YundingConsts.PROCESS_METHOD_VISIT_DEBUG:
                break;

            case YundingConsts.PROCESS_METHOD_REPLACE_FACEPLATE:

                sbOrderLog.append("面板/锁体SN信息：<br>");

                // sn 码
                buildPartChangeLog(sbOrderLog,"  新面板SN：",newOrderData.getPanelSn(),dbOrderData.getPanelSn());
                buildPartChangeLog(sbOrderLog,"  旧面板SN：",newOrderData.getOldPanelSn(),dbOrderData.getOldPanelSn());

                if (!StringUtil.isNullOrEmpty(newOrderData.getPanelSn())) {
                    dbOrderData.setPanelSn(newOrderData.getPanelSn());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getOldPanelSn())) {
                    dbOrderData.setOldPanelSn(newOrderData.getOldPanelSn());
                }

                sbOrderLog.append("替换商品信息：<br>");

                buildPartChangeLog(sbOrderLog,"  面板名称：",newOrderData.getPanelName(),dbOrderData.getPanelName());
                buildPartChangeLog(sbOrderLog,"  面板Sku：",newOrderData.getPanelSku(),dbOrderData.getPanelSku());

                // 面板替换商品
                if (!StringUtil.isNullOrEmpty(newOrderData.getPanelSku())) {
                    dbOrderData.setPanelSku(newOrderData.getPanelSku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getPanelName())) {
                    dbOrderData.setPanelName(newOrderData.getPanelName());
                }

                sbOrderLog.append("；");

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_LOCK_BODY:

                sbOrderLog.append("面板/锁体SN信息：<br>");

                // sn 码
                buildPartChangeLog(sbOrderLog,"  新锁体SN：",newOrderData.getLockSn(),dbOrderData.getLockSn());
                buildPartChangeLog(sbOrderLog,"  旧锁体SN：",newOrderData.getOldLockSn(),dbOrderData.getOldLockSn());

                if (!StringUtil.isNullOrEmpty(newOrderData.getLockSn())) {
                    dbOrderData.setLockSn(newOrderData.getLockSn());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getOldLockSn())) {
                    dbOrderData.setOldLockSn(newOrderData.getOldLockSn());
                }

                sbOrderLog.append("替换商品信息：<br>");

                // 锁体替换商品
                buildPartChangeLog(sbOrderLog,"  锁体名称：",newOrderData.getLockName(),dbOrderData.getLockName());
                buildPartChangeLog(sbOrderLog,"  锁体sku：",newOrderData.getLockSku(),dbOrderData.getLockSku());

                if (!StringUtil.isNullOrEmpty(newOrderData.getLockSku())) {
                    dbOrderData.setLockSku(newOrderData.getLockSku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getLockName())) {
                    dbOrderData.setLockName(newOrderData.getLockName());
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_SIDE_BAR:

                sbOrderLog.append("替换商品信息：<br>");
                // 侧条替换商品
                buildPartChangeLog(sbOrderLog,"  侧条名称：",newOrderData.getSliderName(),dbOrderData.getSliderName());
                buildPartChangeLog(sbOrderLog,"  侧条Sku：",newOrderData.getSliderSku(),dbOrderData.getSliderSku());

                if (!StringUtil.isNullOrEmpty(newOrderData.getSliderSku())) {
                    dbOrderData.setSliderSku(newOrderData.getSliderSku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getSliderName())) {
                    dbOrderData.setSliderName(newOrderData.getSliderName());
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_LOCK_CORE:

                sbOrderLog.append("替换商品信息：<br>");

                // 锁芯替换商品
                buildPartChangeLog(sbOrderLog,"  锁芯名称：",newOrderData.getLockCylinderName(),dbOrderData.getLockCylinderName());
                buildPartChangeLog(sbOrderLog,"  锁芯Sku：",newOrderData.getLockCylinderSku(),dbOrderData.getLockCylinderSku());

                if (!StringUtil.isNullOrEmpty(newOrderData.getLockCylinderSku())) {
                    dbOrderData.setLockCylinderSku(newOrderData.getLockCylinderSku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getLockCylinderName())) {
                    dbOrderData.setLockCylinderName(newOrderData.getLockCylinderName());
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_FINGERPRINT_HEAD:

                sbOrderLog.append("替换商品信息：<br>");

                // 指纹头替换商品
                buildPartChangeLog(sbOrderLog,"  指纹头名称：",newOrderData.getFigptHeadName(),dbOrderData.getFigptHeadName());
                buildPartChangeLog(sbOrderLog,"，指纹头Sku：",newOrderData.getFigptHeadSku(),dbOrderData.getFigptHeadSku());

                if (!StringUtil.isNullOrEmpty(newOrderData.getFigptHeadSku())) {
                    dbOrderData.setFigptHeadSku(newOrderData.getFigptHeadSku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getFigptHeadName())) {
                    dbOrderData.setFigptHeadName(newOrderData.getFigptHeadName());
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_GATEWAY:

                sbOrderLog.append("替换商品信息：<br>");

                buildPartChangeLog(sbOrderLog,"  网关名称：",newOrderData.getGateWayName(),dbOrderData.getGateWayName());
                buildPartChangeLog(sbOrderLog,"  网关Sku：",newOrderData.getGateWaySku(),dbOrderData.getGateWaySku());

                if (!StringUtil.isNullOrEmpty(newOrderData.getGateWaySku())) {
                    dbOrderData.setGateWaySku(newOrderData.getGateWaySku());
                }

                if (!StringUtil.isNullOrEmpty(newOrderData.getGateWayName())) {
                    dbOrderData.setGateWayName(newOrderData.getGateWayName());
                }

                break;
        }

        return sbOrderLog.toString();
    }

    /**
     *
     * @param sbLog
     * @param newPartParma
     * @param oldPartParam
     */
    private void buildPartChangeLog(StringBuilder sbLog, String showName,String newPartParma, String oldPartParam) {

        if (Objects.isNull(sbLog)) {
            return;
        }

        sbLog.append(showName);

        if (!StringUtil.isNullOrEmpty(oldPartParam)) {
            sbLog.append(oldPartParam);
        }

        if (!StringUtil.isNullOrEmpty(newPartParma)) {
            if (!StringUtil.isNullOrEmpty(oldPartParam) ) {
                if (oldPartParam.compareTo(newPartParma) ==0) {
                    sbLog.append("<br>");
                    return;
                } else {
                    sbLog.append(" -> ");
                }
            }

            sbLog.append(newPartParma);
        }

        sbLog.append("<br>");
    }

    /**
     * 生成需要的日志
     *
     * @param yundingOrderCacheData
     * @return
     */
    private String pickOrderLogByYundingOrderData(YundingOrderCacheData yundingOrderCacheData) {

        if (Objects.isNull(yundingOrderCacheData)) {
            return "";
        }

        StringBuilder sbOrderLog = new StringBuilder();
        sbOrderLog.append("解决方案：<br>").append(yundingOrderCacheData.getProcessMethodName()).append(";");

        // sn 码
        switch (yundingOrderCacheData.getProcessMethodCode()) {

            case YundingConsts.PROCESS_METHOD_REPLACE_WHOLE_LOCK:
            case YundingConsts.PROCESS_METHOD_PRODUCT_UPGRADES:

                sbOrderLog.append("面板/锁体SN信息：");
                // sn 码
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getPanelSn())) {
                    sbOrderLog.append("<br>  新面板SN：").append(yundingOrderCacheData.getPanelSn())
                            .append("<br>  旧面板SN：").append(yundingOrderCacheData.getOldPanelSn())
                            .append("<br>  新锁体SN：").append(yundingOrderCacheData.getLockSn())
                            .append("<br>  旧锁体SN：").append(yundingOrderCacheData.getOldLockSn())
                            .append("<br>");
                }

                sbOrderLog.append("替换商品信息：");

                // 面板替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getPanelSku())) {
                    sbOrderLog.append("<br>  面板名称：").append(yundingOrderCacheData.getPanelName())
                            .append("<br>  面板Sku：").append(yundingOrderCacheData.getPanelSku())
                            .append("<br>");
                }

                // 锁体替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getLockSku())) {
                    sbOrderLog.append("  锁体名称：").append(yundingOrderCacheData.getLockName())
                            .append("<br>  锁体Sku：").append(yundingOrderCacheData.getLockSku())
                            .append("<br>");
                }

                // 侧条替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getSliderSku())) {
                    sbOrderLog.append("  侧条名称：").append(yundingOrderCacheData.getSliderName())
                            .append("<br>  侧条Sku：").append(yundingOrderCacheData.getSliderSku())
                            .append("<br>");
                }

                break;
            case YundingConsts.PROCESS_METHOD_VISIT_DEBUG:
                break;

            case YundingConsts.PROCESS_METHOD_REPLACE_FACEPLATE:

                sbOrderLog.append("面板/锁体SN信息：<br>");
                // sn 码
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getPanelSn())) {
                    sbOrderLog.append("<br>  新面板SN：").append(yundingOrderCacheData.getPanelSn())
                            .append("<br>  旧面板SN：").append(yundingOrderCacheData.getOldPanelSn())
                            .append("<br>");
                }

                sbOrderLog.append("替换商品信息：");

                // 面板替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getPanelSku())) {
                    sbOrderLog.append("<br>  面板名称：").append(yundingOrderCacheData.getPanelName())
                            .append("<br>  面板Sku：").append(yundingOrderCacheData.getPanelSku())
                            .append("<br>");
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_LOCK_BODY:

                sbOrderLog.append("面板/锁体SN信息：");
                // sn 码
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getLockSn())) {
                    sbOrderLog.append("<br>  新锁体SN：").append(yundingOrderCacheData.getLockSn())
                            .append("<br>  旧锁体SN：").append(yundingOrderCacheData.getOldLockSn())
                            .append("<br>");
                }

                sbOrderLog.append("替换商品信息：");

                // 锁体替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getLockSku())) {
                    sbOrderLog.append("<br>  锁体名称：").append(yundingOrderCacheData.getLockName())
                            .append("<br>  锁体Sku：").append(yundingOrderCacheData.getLockSku())
                            .append("<br>");
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_SIDE_BAR:

                sbOrderLog.append("替换商品信息：");
                // 侧条替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getSliderSku())) {
                    sbOrderLog.append("<br>  侧条名称：").append(yundingOrderCacheData.getSliderName())
                            .append("<br>  侧条Sku：").append(yundingOrderCacheData.getSliderSku())
                            .append("<br>");
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_LOCK_CORE:

                sbOrderLog.append("替换商品信息：");

                // 锁芯替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getLockCylinderSku())) {
                    sbOrderLog.append("<br>  锁芯名称：").append(yundingOrderCacheData.getLockCylinderName())
                            .append("<br>  锁芯Sku：").append(yundingOrderCacheData.getLockCylinderSku())
                            .append("<br>");
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_FINGERPRINT_HEAD:

                sbOrderLog.append("替换商品信息：");
                // 指纹头替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getFigptHeadSku())) {
                    sbOrderLog.append("<br>  指纹头名称：").append(yundingOrderCacheData.getFigptHeadName())
                            .append("<br>  指纹头Sku：").append(yundingOrderCacheData.getFigptHeadSku())
                            .append("<br>");
                }

                break;
            case YundingConsts.PROCESS_METHOD_REPLACE_GATEWAY:

                sbOrderLog.append("替换商品信息：");
                // 网关替换商品
                if (!StringUtil.isNullOrEmpty(yundingOrderCacheData.getGateWaySku())) {
                    sbOrderLog.append("<br>  网关名称：").append(yundingOrderCacheData.getGateWayName())
                            .append("<br>  网关Sku：").append(yundingOrderCacheData.getGateWaySku())
                            .append("<br>");
                }
                break;
        }
        return sbOrderLog.toString();
    }
    /**
     * 保存日志
     *
     * @param orderId
     * @param orderLog
     * @param isMaster
     */
    private void saveOrderLog(Long orderId,String orderLog, boolean isMaster) {

        // 参数判断
        if (NumberUtil.isNullOrZero(orderId) || StringUtil.isNullOrEmpty(orderLog)) {
            return;
        }

        // 查找工单
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,orderId);
        if (Objects.isNull(orderWork)){
            return ;
        }

        // 构造日志数据
        OrderLogDTO orderLogDTO = new OrderLogDTO();
        orderLogDTO.setOrderId(orderWork.getOrderId());
        orderLogDTO.setOuterId(orderWork.getOuterId());
        orderLogDTO.setChannelId(orderWork.getChannelId());
        orderLogDTO.setOperatorLogRemark(orderLog);
        orderLogDTO.setType(OrderLogConsts.ORDER_LOG_TYPE_CHANNEL_REMARK);

        if (isMaster) {
            orderLogDTO.setOperatorId((long)Optional.ofNullable(orderWork.getMasterId()).orElse(0));
            orderLogDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_MASTER);
            orderLogDTO.setOperator(orderWork.getMasterName());
        } else {
            orderLogDTO.setOperatorId((long)orderWork.getChannelId());
            orderLogDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            orderLogDTO.setOperator("系统");
        }

        try {
            proxyOrderBService.addOrderLog(orderLogDTO);
        } catch (OmsBaseException e) {
            log.info("【{}】保存日志异常，【{}】【{}】",YundingConsts.CHANNEL_NAME,orderLog,e.getMessage());
        }
    }

    public static void main(String[] args) {

        String request = "{\"app_key\":\"127655DDB2F39F91F935577C0A2D4200\",\"data\":\"{\\\"ext_fields\\\":\\\"{\\\\\\\"contact_name\\\\\\\":\\\\\\\"言远程001\\\\\\\",\\\\\\\"contact_phone\\\\\\\":\\\\\\\"13350300176\\\\\\\"}\\\",\\\"order_number\\\":\\\"517356534993264640\\\",\\\"status_code\\\":\\\"WAITING_COMMUNICATE\\\",\\\"status_name\\\":\\\"待师傅联系\\\"}\",\"sign\":\"f75766b830da510cd3c152f59598752e\",\"timestamp\":1601277590211,\"type\":\"ORDER_STATUS\"}";
        String syncUrl = YundingConsts.API_URL + YundingConsts.SYNC_ORDER_STATUS_PATH;
        String syncResponse = YundingUtil.postHttpsRequest(syncUrl,request);
        System.out.println(syncResponse);
    }
}